package com.itheima.mp.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.PageQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
                                implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * 根据id扣减余额
     * @param id
     * @param money
     */
    @Transactional
    @Override
    public void deductBalance(Long id, Integer money) {
//        1.根据id值获取用户信息
        final User user = getById(id);
//        2.确定用户存在
        if (user != null) {
//            2.确定该用户状态是否正常
            if (user.getStatus()==2)
                throw new RuntimeException("用户状态异常");
//            3.确定用户余额是否充足
            if (user.getBalance() < money) {
                throw new RuntimeException("用户余额不足,扣减余额失败");
            }
            // 4.扣减余额
            int reminMoney=user.getBalance()-money;
            lambdaUpdate()
                    .set(User::getBalance,reminMoney)//修改余额
                    .set(reminMoney==0,User::getStatus,2)//余额为0，则将用户状态冻结
                    .eq(User::getId,id)//与传入的id匹配
                    .eq(User::getBalance,user.getBalance())//乐观锁CS
                    .update();
//            baseMapper.deductMoneyById(id, money);
        }else {
//            5.用户不存在，打印抛异常
            System.out.println("用户不存在");
            throw new RuntimeException("用户不存在");
        }

    }

    /**
     * 条件查询
     * @param name
     * @param status
     * @param minBalance
     * @param maxBalance
     * @return
     */
    public List<User> qurtyUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {

        return lambdaQuery()
                .like(name!=null, User::getUsername, name)
                .eq(status!=null, User::getStatus, status)
                .ge(minBalance!=null, User::getBalance, minBalance)
                .le(maxBalance!=null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public UserVO queryUserAndAddressById(Long userId) {
        // 1.查询用户
        User user = getById(userId);
        if (user == null) {
            return null;
        }
        // 2.查询收货地址
        List<Address> addresses = Db.lambdaQuery(Address.class)
//查询地址时，我们采用了Db的静态方法，因此避免了注入AddressService，减少了循环依赖的风险
                .eq(Address::getUserId, userId)
                .list();
        // 3.处理vo
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        return userVO;
    }

    @Override
    public PageDTO<UserVO> queryUserpage(PageQuery query) {
        // 1.构建条件
        // 1.1.分页条件
        Page<User> page = Page.of(query.getPageNo(), query.getPageSize());
        // 1.2.排序条件
        if (query.getSortBy() != null) {
            page.addOrder(new OrderItem(query.getSortBy(), query.getIsAsc()));
        }else{
            // 默认按照更新时间排序
            page.addOrder(new OrderItem("update_time", false));
        }
        // 2.查询
        page(page);
        // 3.数据非空校验
        List<User> records = page.getRecords();
        if (records == null || records.size() <= 0) {
            // 无数据，返回空结果
            return new PageDTO<>(page.getTotal(),page.getPages(),Collections.emptyList());
//            page.getTotal(),page.getPages(),Collections.emptyList()
        }
        // 4.有数据，转换
        List<UserVO> list = BeanUtil.copyToList(records, UserVO.class);
        // 5.封装返回
        return new PageDTO<UserVO>(page.getTotal(), page.getPages(), list);
    }

}
